#include "platform.h"
#include "resource.h"

#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;

#include "ChromeManager.h"
#include "BizEnv.h"
#include "OwinHost.h"

#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

static INT_PTR CALLBACK MainProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(HINSTANCE hInstance,
					  HINSTANCE hPrevInstance,
					  LPTSTR    lpCmdLine,
					  int       nCmdShow) 
{
	try
	{
		BizEnv::instance().startup();
		OwinHost::instance().startup(&BizEnv::instance());
		ChromeManager::instance().startup(hInstance);
		DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAINFORM), NULL, MainProc);
		ChromeManager::instance().shutdown();
		OwinHost::instance().shutdown();
		BizEnv::instance().shutdown();
	}
	catch(const exception& e)
	{
		MessageBoxA(NULL, e.what(), "Error", MB_OK);
	}

	return 0;
}

INT_PTR CALLBACK MainProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message) {
	case WM_INITDIALOG:
		{
			// Append a sub-menu "About" to system menu
			HMENU hMenu = GetSystemMenu(hDlg, FALSE);
			AppendMenuW(hMenu, MF_ENABLED | MF_STRING, IDM_ABOUT, L"&About");

			ChromeManager::instance().create(hDlg, OwinHost::instance().root());
		}
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;

	case WM_SYSCOMMAND:
		if (LOWORD(wParam) == IDM_ABOUT)
		{
			wstringstream ss;
			ss << L"SAP BusinessOne Client v-epic (" <<
#ifdef _M_X64
				L"x64"
#else
				L"x86"
#endif
				<<	L")\r\nCompiled at "
				<< __DATE__ << ", " << __TIME__;

			return MessageBox(hDlg, ss.str().c_str(), L"About", MB_OK | MB_ICONINFORMATION);	
		}
		break;

	case WM_SIZE:
		if (wParam != SIZE_MINIMIZED)
		{
			HWND hmc = hDlg;
			hmc = FindWindowEx(hmc, NULL, NULL, NULL);
			if (IsWindow(hmc))
			{
				//wchar_t cc[200];
				//GetClassName(hmc, cc, 200);

				RECT rect;
				GetClientRect(hDlg, &rect);

				HDWP hdwp = BeginDeferWindowPos(1);
				hdwp = DeferWindowPos(hdwp, hmc, NULL,
					rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
					SWP_NOZORDER);
				EndDeferWindowPos(hdwp);
			}
		}
		break;
	}
	return (INT_PTR)FALSE;
}